<template>
  <div class="map-wrapper">
    <!-- 顶部左侧悬浮栏组 -->
    <div class="map-header-left">
      <!-- 切换校区：绘图模式下禁用，防止打断绘制 -->
      <el-dropdown @command="handleCampus" :disabled="isDrawing">
        <el-button type="primary">
          切换区域
          <el-icon class="ml-1"><ArrowDown /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="center">北苑区域</el-dropdown-item>
            <el-dropdown-item command="west">图书馆区域</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 分区显示：绘图模式下禁用，防止打断绘制 -->
      <el-button
          :type="areaVisible ? 'success' : 'primary'"
          @click="toggleAreaVisibility"
          :disabled="isDrawing"
      >
        {{ areaVisible ? '隐藏分区' : '显示分区' }}
      </el-button>

      <!-- 添加或修改水表管理对话框 -->
      <ElementEdit
          v-model:open="elemWindow"
          :init-form="form"
          :title="title"
          @submit="submitForm"
          @close="elemWindow = false"
      />

      <!-- 区域编辑对话框 -->
      <AreaEdit
          v-model:open="areaEditOpen"
      :init-form="areaForm"
      :title="areaEditTitle"
      @submit="handleAreaEditSubmit"
      @close="handleAreaEditClose"
      />
    </div>

    <div class="map-header-right">
      <el-button
          @click="areaAdd"
          type="primary"
          :disabled="isDrawing && polygonPoints.length < 3"
      >
        {{ isDrawing ? '完成绘制' : '增加区域' }}
      </el-button>

      <el-button
          v-if="isDrawing"
          @click="cancelDrawing"
          type="warning"
      >
        取消绘制
      </el-button>
    </div>

    <!-- 绘图提示 -->
    <div v-if="isDrawing" class="drawing-tip">
      <p>请在地图上点击添加多边形顶点，点击右上角完成绘制</p>
      <p>当前顶点数: {{ polygonPoints.length }} （至少需3个顶点）</p>
    </div>

    <!-- 地图容器 -->
    <div class="map-container" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted, getCurrentInstance } from 'vue';
import { ArrowDown } from '@element-plus/icons-vue';
// 引入AreaEdit组件（路径需根据实际项目结构调整）
import AreaEdit from "@/components/water/dialog/AreaEdit.vue";
import ElementEdit, { reset } from "@/components/water/dialog/ElementEdit.vue"
import { listElement, getElement, delElement, addElement, updateElement } from "@/api/water/element.js";
import { listArea, getArea, delArea, addArea, updateArea } from "@/api/water/area.js";
import { markersInit, polygonsInit } from '@/api/water/map.js';
import ElementPic from '@/assets/icons/svg/system_green.svg';
import DotPic from '@/assets/icons/svg/dot.svg'
import { ElMessage, ElMessageBox } from "element-plus";

let map = null;
let markers = [];
let polygons = [];
let drawingPolygon = null; // 正在绘制的多边形
let drawingPoints = []; // 绘制过程中的临时点标记

// 响应式变量 - 原有逻辑保留
const mapContainer = ref(null);
const areaVisible = ref(true);
const loading = ref(true);
const elemWindow = ref(false);
const { proxy } = getCurrentInstance();
const form = ref({});
const title = ref("元素编辑");
const isDrawing = ref(false); // 是否处于绘图模式
const polygonPoints = ref([]); // 多边形顶点数组

// 新增：区域编辑组件相关响应式变量
const areaEditOpen = ref(false); // 控制AreaEdit弹窗显示
const areaEditTitle = ref("添加区域"); // AreaEdit弹窗标题
const areaForm = ref({}); // 传递给AreaEdit的初始数据


// 切换校区逻辑
const handleCampus = (command) => {
  console.log('切换校区：', command);
  if (command === 'center') {
    map.centerAndZoom(new BMapGL.Point(114.168202, 30.524314), 18); // 北苑区域中心坐标
  } else if (command === 'west') {
    map.centerAndZoom(new BMapGL.Point(114.167382, 30.519973), 18); // 图书馆区域中心坐标
  }
};

// 分区显示逻辑
const toggleAreaVisibility = () => {
  areaVisible.value = !areaVisible.value;
  if (areaVisible.value) {
    console.log('显示分区');
    polygons.forEach(polygon => { map.addOverlay(polygon); });
  } else {
    console.log('隐藏分区');
    polygons.forEach(polygon => { map.removeOverlay(polygon); });
  }
};

// 开始或完成区域绘制
const areaAdd = () => {
  if (!isDrawing.value) {
    // 开始绘制
    startDrawing();
  } else {
    // 完成绘制（主动点击按钮时触发）
    finishDrawing();
  }
};

// 取消绘制
const cancelDrawing = () => {
  if (isDrawing.value) {
    // 移除绘图相关事件监听
    map.removeEventListener('click', addDrawingPoint);
    map.removeEventListener('dblclick', finishDrawing);
    // 清除绘制痕迹
    clearDrawing();
    isDrawing.value = false;
    ElMessage.info('已取消绘制');
  }
};

// 开始绘制多边形
const startDrawing = () => {
  isDrawing.value = true;
  polygonPoints.value = [];
  drawingPoints = [];

  // 先移除旧事件监听（防止重复绑定），再添加新事件
  map.removeEventListener('click', addDrawingPoint);
  map.removeEventListener('dblclick', finishDrawing);
  map.addEventListener('click', addDrawingPoint);
  map.addEventListener('dblclick', finishDrawing);

  ElMessage.info('请在地图上点击添加多边形顶点，右上角点击完成绘制');
};

// 添加绘制点
const addDrawingPoint = (e) => {
  if (!isDrawing.value) return;

  // 记录经纬度
  const point = new BMapGL.Point(e.latlng.lng, e.latlng.lat);
  polygonPoints.value.push({ lng: e.latlng.lng, lat: e.latlng.lat });

  // 添加临时标记
  const marker = new BMapGL.Marker(point, {
    icon: new BMapGL.Icon(DotPic, new BMapGL.Size(10, 10), {
      anchor: new BMapGL.Size(5, 5)
    })
  });
  map.addOverlay(marker);
  drawingPoints.push(marker);

  // 更新多边形
  updateDrawingPolygon();
};

// 更新正在绘制的多边形
const updateDrawingPolygon = () => {
  // 移除之前的临时多边形
  if (drawingPolygon) {
    map.removeOverlay(drawingPolygon);
  }

  // 创建新的临时多边形（至少2个点才显示）
  if (polygonPoints.value.length >= 2) {
    const points = polygonPoints.value.map(p => new BMapGL.Point(p.lng, p.lat));
    drawingPolygon = new BMapGL.Polygon(points, {
      strokeColor: 'red',
      strokeWeight: 3,
      strokeOpacity: 0.8,
      fillColor: 'red',
      fillOpacity: 0.2
    });
    map.addOverlay(drawingPolygon);
  }
};

// 完成绘制
const finishDrawing = () => {
  if (polygonPoints.value.length < 3) {
    ElMessage.warning('多边形至少需要3个顶点，请继续添加');
    return;
  }

  // 1. 先移除绘图事件监听（避免继续添加顶点）
  map.removeEventListener('click', addDrawingPoint);
  map.removeEventListener('dblclick', finishDrawing);

  // 2. 初始化AreaEdit表单数据（传递绘制好的多边形坐标）
  areaForm.value = {
    areaGeo: JSON.stringify(polygonPoints.value), // 多边形坐标转JSON字符串
    areaName: '', // 区域名称空值（让用户在AreaEdit中填写）
    recordTime: Date.now() // 默认当前时间
  };

  // 3. 打开AreaEdit弹窗
  areaEditOpen.value = true;
  isDrawing.value = false; // 退出绘图模式
};

// 清除绘制痕迹
const clearDrawing = () => {
  // 移除临时多边形
  if (drawingPolygon) {
    map.removeOverlay(drawingPolygon);
    drawingPolygon = null;
  }

  // 移除临时标记点
  drawingPoints.forEach(marker => {
    map.removeOverlay(marker);
  });
  drawingPoints = [];

  // 清空顶点数组
  polygonPoints.value = [];
};

//处理AreaEdit表单提交
const handleAreaEditSubmit = (formData) => {
  // formData包含用户在AreaEdit中填写的所有数据（areaName、areaGeo等）
  addArea(formData).then(response => {
    if (response.code === 200) {
      ElMessage.success('区域添加成功');
      // 提交成功：关闭弹窗 + 重新加载区域数据 + 清除绘制痕迹
      areaEditOpen.value = false;
      areaInit(); // 重新初始化区域显示
      clearDrawing();
    } else {
      ElMessage.error('区域添加失败: ' + (response.msg || '未知错误'));
      // 失败：重新绑定绘图事件，允许用户重试
      map.addEventListener('click', addDrawingPoint);
      map.addEventListener('dblclick', finishDrawing);
    }
  }).catch(error => {
    console.error('添加区域失败', error);
    ElMessage.error('添加区域失败，请稍后重试');
    // 失败：重新绑定绘图事件，允许用户重试
    map.addEventListener('click', addDrawingPoint);
    map.addEventListener('dblclick', finishDrawing);
  });
};

// 新增：处理AreaEdit弹窗关闭（用户点击取消）
const handleAreaEditClose = () => {
  // 关闭弹窗 + 清除绘制痕迹 + 重置状态
  areaEditOpen.value = false;
  clearDrawing();
  ElMessage.info('已取消创建区域');
};

/** 水表编辑提交按钮 */
function submitForm(formData) {
  if (formData.id != null) {
    updateElement(formData).then(response => {
      proxy.$modal.msgSuccess("修改成功");
    });
  } else {
    addElement(formData).then(response => {
      proxy.$modal.msgSuccess("新增成功");
    });
  }
  elemWindow.value = false;
  map.clearOverlays();
  elemInit();
}

// 水表数据初始化
async function elemInit() {
  try {
    loading.value = true;
    const elementList = await listElement({ pageSize: 10000 });
    if (elementList.code === 200 && elementList.rows) {
      markers = markersInit(map, elementList.rows, ElementPic,
          (currentElement) => {
            reset(form);
            proxy.resetForm("elementRef");
            form.value = JSON.parse(JSON.stringify(currentElement));
            elemWindow.value = true;
            title.value = "水表编辑";
          });
      markers.forEach(marker => {
        map.addOverlay(marker);
      });
    }
  } catch (error) {
    console.error('获取水表数据时发生错误', error);
    ElMessage.error('获取水表数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 区域数据初始化
async function areaInit() {
  try {
    loading.value = true;
    const areaList = await listArea({ pageSize: 10000 });
    if (areaList.code === 200 && areaList.rows) {
      // 先清除现有多边形
      polygons.forEach(polygon => {
        map.removeOverlay(polygon);
      });

      // 添加新的多边形
      polygons = polygonsInit(map, areaList.rows, (currentArea) => {
        areaForm.value = currentArea;

        // 3. 打开AreaEdit弹窗
        areaEditOpen.value = true;
      });

      // 根据显示状态决定是否添加到地图
      if (areaVisible.value) {
        polygons.forEach(polygon => {
          map.addOverlay(polygon);
        });
      }
    }
  } catch (error) {
    console.error('获取区域数据时发生错误', error);
    ElMessage.error('获取区域数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

onMounted(async () => {
  // 初始化百度地图（确保百度地图SDK已加载）
  if (!window.BMapGL) {
    ElMessage.error('地图SDK加载失败，请刷新页面重试');
    return;
  }
  map = new BMapGL.Map(mapContainer.value, { minZoom: 16, maxZoom: 20 });
  map.centerAndZoom(new BMapGL.Point(114.167382, 30.519973), 18);
  map.enableScrollWheelZoom(true);
  map.enableKeyboard(true);
  map.addControl(new BMapGL.ScaleControl());
  map.addControl(new BMapGL.ZoomControl());

  // 数据初始化（先加载区域，再加载水表，避免覆盖）
  await areaInit();
  await elemInit();
});

onUnmounted(() => {
  if (map) {
    // 组件卸载时彻底移除所有事件监听和覆盖物
    map.removeEventListener('click', addDrawingPoint);
    map.removeEventListener('dblclick', finishDrawing);
    map.clearOverlays();
    map = null;
  }
});
</script>

<style scoped>
/* 原有样式保留 */
.map-wrapper {
  width: 100%;
  height: calc(100vh - 84px);
  position: relative;
}

.map-header-left {
  position: absolute;
  top: 1%;
  left: 1%;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 15px;
}

.map-header-right {
  position: absolute;
  top: 1%;
  right: 4%;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 5px;
}

.map-container {
  width: 100%;
  height: 100%;
  font-family: "微软雅黑";
}

.drawing-tip {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 15px;
  border-radius: 4px;
  z-index: 1000;
  font-size: 14px;
}

.drawing-tip p {
  margin: 5px 0;
}
</style>